﻿#include "stdio.h"
#include "malloc.h"

typedef struct Node
{
    int data[100];
    int length;
} SeqList, * PSeqList;

PSeqList initList()
{
    PSeqList resultList;
    resultList = (PSeqList)malloc(sizeof(SeqList));
    if (resultList)
    {
        resultList->length = 0;
    }
    return resultList;
}

int getLengthByList(PSeqList list)
{
    return list->length;
}

int queryListByItem(PSeqList targetList, int queryItem)
{
    if (targetList->length == 0 || queryItem == NULL)
    {
        return -1;
    }

    int i = 0;
    while (1) {

        if (targetList->data[i] == queryItem)
            return i;

        if (i == targetList->length - 1)
            break;


        i++;
    }
    return -1;
}

int insertIndexItem(PSeqList targetList, int index, int item)
{
    if (!targetList)
    {
        return -1;
    }
    targetList->data[index] = item;
    targetList->length++;
    return 1;
}

int insertItem(PSeqList targetList, int item)
{
    if (!targetList)
    {
        return -1;
    }
    return insertIndexItem(targetList, getLengthByList(targetList), item);
}

void destroyList(PSeqList* targetList)
{

    if (targetList)
    {
        free(*targetList);
    }
    *targetList = NULL;
}

PSeqList mergeList(
    PSeqList list1, PSeqList list2)
{

    if (list1->length <= 0 && list2->length <= 0)
    {
        return NULL;
    }

    PSeqList resultList = initList();

    int i = 0;
    int k = 0;
    int j = 0;

    int sumLength = list1->length + list2->length;

    while (1)
    {

        if (k >= sumLength)
        {
            break;
        }

        if (k < list1->length)
        {
            insertItem(resultList, list1->data[i]);
            i++;
        }
        else
        {
            insertItem(resultList, list2->data[j]);
            j++;
        }

        k++;
    }
    return resultList;
}

void main()
{

    PSeqList qList1 = initList();
    PSeqList qList2 = initList();

    insertItem(qList1, 1);
    insertItem(qList1, 2);
    insertItem(qList1, 3);

    insertItem(qList2, 4);
    insertItem(qList2, 5);
    insertItem(qList2, 6);

    printf("List1: \n");
    int i = 0;
    while (i < qList1->length)
    {
        printf("%d ", qList1->data[i]);
        i++;
    }

    printf("\nList2: \n");
    int j = 0;
    while (j < qList2->length)
    {
        printf("%d ", qList2->data[j]);
        j++;
    }

    printf("\n merge result: ");
    SeqList* resultList = mergeList(qList1, qList2);

    printf("%d", resultList->length);

    int k = 0;
    while (k < resultList->length)
    {
        printf("%d ", resultList->data[k]);
        k++;
    }
}
